from django.shortcuts import render, get_object_or_404
from django.db.models import Prefetch
from django.contrib.auth.decorators import login_required
from core.models import Subject, Chapter, KnowledgePoint, TeacherSubjectAssignment

@login_required
def subject_chapter_knowledge(request, subject_id):
    # 获取用户有权限的学科
    user_subjects = TeacherSubjectAssignment.objects.filter(teacher=request.user).values_list('subject_id', flat=True)
    subjects = Subject.objects.filter(id__in=user_subjects).order_by('name')
    selected_subject = None
    chapters = []

    # 尝试获取指定的学科或默认选择第一个
    if subject_id:
        selected_subject = get_object_or_404(Subject, id=subject_id, id__in=user_subjects)
    else:
        # 如果没有指定学科或学科无效，默认选择第一个有权限的学科
        if subjects.exists():
            selected_subject = subjects.first()

    # 如果有选中的学科，获取其章节和知识点
    if selected_subject:
        chapters = Chapter.objects.filter(subject=selected_subject).order_by('order').prefetch_related(
            Prefetch('knowledge_points', queryset=KnowledgePoint.objects.order_by('order').prefetch_related('mistakes'))
        )

    return render(request, 'chapter/subject_chapter_knowledge.html', {
        'subjects': subjects,
        'selected_subject': selected_subject,
        'chapters': chapters
    })